package com.I9lou.se.lurker.facet.search.support;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.Scorer;

/**
 * @author moshan 自定义collector,多个聚类
 */
public class MultiFacetCollector extends Collector {

	/** 统计字段 */
	protected String						facetField;

	/** 统计结果 */
	protected final Map<String, Integer>	facetMap	= new HashMap<String, Integer>();

	protected int							totalCount	= 0;

	private FieldCache.StringIndex			index;

	private char							splitChar	= ',';

	/**
	 * @param facetField
	 */
	public MultiFacetCollector(String facetField) {
		this.facetField = facetField;
	}

	public MultiFacetCollector(String facetField, char schar) {
		this(facetField);
		this.splitChar = schar;
	}

	@Override
	public void collect(int doc) throws IOException {
		String facetVal = getFacetFieldValue(doc);
		if (null == facetVal) {
			return;
		}
		int start = 0;
		int index = facetVal.indexOf(splitChar);
		while (index > 0) {
			String st = facetVal.substring(start, index);
			this.incFacetValue(st);
			start = index + 1;
			index = facetVal.indexOf(splitChar, start);
		}
		if (start < facetVal.length()) {
			String st = facetVal.substring(start, facetVal.length());
			this.incFacetValue(st);
		}
		totalCount++;
	}

	protected void incFacetValue(String facetVal) {
		Integer num = facetMap.get(facetVal);
		if (null == num) {
			facetMap.put(facetVal, 1);
		} else {
			facetMap.put(facetVal, ++num);
		}

	}

	@Override
	public boolean acceptsDocsOutOfOrder() {
		return true;
	}

	@Override
	public void setNextReader(IndexReader reader, int docBase) throws IOException {
		index = FieldCache.DEFAULT.getStringIndex(reader, facetField);
	}

	@Override
	public void setScorer(Scorer scorer) throws IOException {
	}

	protected String getFacetFieldValue(int doc) {
		final int ord = index.order[doc];
		return ord == 0 ? null : index.lookup[ord];
	}

}
